#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/cdev.h>

static ssize_t cdev_test_read(struct file *file, char __user *buf, size_t size, loff_t *off);
static ssize_t cdev_test_write(struct file *file, char __user *buf, size_t size, loff_t *off);
static int cdev_test_open(struct inode* node, struct file* file);
static int cdev_test_release(struct inode* node, struct file* file);

dev_t dev;
struct cdev cdev_test;
struct file_operations cdev_test_ops = {
    .owner = THIS_MODULE,
    .read = cdev_test_read,
    .write = cdev_test_write,
    .open = cdev_test_open,
    .release = cdev_test_release
};

static ssize_t cdev_test_read(struct file *file, char __user *buf, size_t size, loff_t *off)
{
    printk("cdev_test_read!\n");
    return 0;
}
static ssize_t cdev_test_write(struct file *file, char __user *buf, size_t size, loff_t *off)
{
    printk("cdev_test_write!\n");
    return 0;
}
static int cdev_test_open(struct inode* node, struct file* file) 
{
    printk("cdev_test_open!\n");
    return 0;
}
static int cdev_test_release(struct inode* node, struct file* file) 
{
    printk("cdev_test_release!\n");
    return 0;
}

static int module_cdev_init(void)
{
    int ret;
    ret = alloc_chrdev_region(&dev,0, 1, "alloc_chrdev_num");
    if (ret) {
        printk("alloc_chrdev_region success!\n");
    } else {
        printk("alloc_chrdev_region fail!\n");
    }
    cdev_test.owner = THIS_MODULE;
    cdev_init(&cdev_test, &cdev_test_ops);
    cdev_add(&cdev_test, dev, 1);
    return 0;
}

static void module_cdev_exit(void)
{
    unregister_chrdev_region(dev, 1);
    cdev_del(&cdev_test);
    printk("module_cdev_exit\n");
}

module_init(module_cdev_init);
module_exit(module_cdev_exit);
// 遵守GPL协议
MODULE_LICENSE("GPL");

MODULE_AUTHOR("wangzhinan");
MODULE_VERSION("V1.0");